package cn.sky.demo.sso;

import cn.sky.demo.service.UserService;
import cn.sky.demo.test.User;
import cn.sky.demo.test.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/auth")
public class CentralAuthController {

    @Autowired
    private UserService userService;
    
    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) String redirect, Model model) {
        model.addAttribute("redirectUrl", redirect);
        return"login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       @RequestParam(required = false) String redirect,
                       HttpSession session,
                       RedirectAttributes redirectAttrs) {
        
        // 验证用户凭证
        User user= userService.authenticate(username, password);
        if (user == null) {
            redirectAttrs.addFlashAttribute("error", "Invalid credentials");
            return"redirect:/auth/login";
        }
        
        // 将用户信息存入共享会话
        UserInfo userInfo=new UserInfo(user.getId(), user.getUsername(), user.getRoles());
        session.setAttribute("USER_INFO", userInfo);
        
        // 如果有重定向URL，则重定向回原应用
        if (redirect != null && !redirect.isEmpty()) {
            return"redirect:" + redirect;
        }
        
        return"redirect:/dashboard";
    }
    
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpSession session) {
        // 使会话失效
        session.invalidate();
        
        // 可选：获取要重定向的URL
        String referer= request.getHeader("Referer");
        
        return"redirect:/auth/login";
    }
}